import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import qs from 'qs'
// create an axios instance
// axios.defaults.withCredentials = true
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.method === 'get') {
      config.data = qs.stringify(config.data)
    } else {
      config.data = JSON.stringify(config.data)
      config.headers['Content-Type'] = 'application/json'
    }
    const Authorization = getToken()
    if (Authorization) {
      config.headers['Authorization'] = Authorization
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code.
   */
  response => {
    const {
      config
    } = response
    const res = response.data
    const {
      code,
      data,
      msg
    } = res
    if (config.responseType === 'blob') {
      return Promise.resolve(res)
    }
    if (code !== 200) {
      Message({
        message: msg || 'error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(msg || 'error')
    }
    if (!data && msg !== '操作成功') {
      if (!config.notShowSuccessInfo) {
        Message({
          message: msg,
          type: 'success',
          duration: 5 * 1000
        })
      }
      return Promise.resolve(msg)
    }
    return Promise.resolve(data)
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
